
#include "BondMarketStream.h"

#include <core/time/date.h>
#include <core/time/system_time.h>
#include <uam/ServerTimeMgr.h>

#include <QDateTime>

#include "BondCalendar.h"
#include "BondContainer.h"
#include "internal/MarketStreamUtil.h"
#include "qbprotocol/include/SSQBModel.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
// #define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////////
int CMarketStreamBase::GetBondDealInvalidateDay() {
  static int m_gMarketStreamToday = 0;
  static int m_gMarketStreamValidDate = 0;
  time_t t_Today = ServerTimeMgr::instance().serverTime();
  int nToday = qb::base::IntDate::timeToInt(t_Today);
  if (nToday <= 19700101) return 0;
  if (nToday == m_gMarketStreamToday) {
    return m_gMarketStreamValidDate;
  }
  m_gMarketStreamToday = nToday;
  qb::base::CTime Td(t_Today);
  int wd = Td.GetDayOfWeek();
  CBondHoliday bondHoliday = CBondCalendar::instance().GetBondHoliday();
  for (int i = 0; i < 100; i++) {
    std::map<int, BondHolidayList>::const_iterator itr =
        bondHoliday.date.find(nToday);
    if (itr == bondHoliday.date.end()) {
      if (wd != 1 && wd != 7) {
        m_gMarketStreamValidDate = nToday;
        return nToday;
      }
      // t_Today -= 60 * 60 * 24;
    } else {
      bool bFind = false;
      for (std::vector<BondHoliday>::const_iterator itrH =
               itr->second.holidays.begin();
           itrH != itr->second.holidays.end(); ++itrH) {
        if (std::string(itrH->country) == std::string("CNY") &&
            std::string(itrH->market) == std::string("CIB")) {
          bFind = true;
          if (std::string(itrH->status) == std::string("T")) {
            m_gMarketStreamValidDate = nToday;
            return nToday;
          }
        }
      }
      if (!bFind && wd != 1 && wd != 7) {
        m_gMarketStreamValidDate = nToday;
        return nToday;
      }
    }
    t_Today -= 60 * 60 * 24;
    nToday = qb::base::IntDate::timeToInt(t_Today);
  }
  m_gMarketStreamValidDate = nToday;
  return nToday;
}

bool CMarketStreamBase::GetTodayMarketRecord(CMarketToprec &MarketInfo,
                                             const CMarketStreamlst &lst,
                                             UINT nActvNum) {
  CMarketToprec RecordInfo;
  std::map<std::string, MarketStreamRec> mapRecordTp;
  if (lst.m_Record.size() > 0) {
    MarketInfo.SetSize(lst.m_list.size());
    for (std::map<std::string, MarketStreamRec>::const_iterator itrRe =
             lst.m_Record.begin();
         itrRe != lst.m_Record.end(); itrRe++) {
      internal::MSUtil::InsertMarketRecord(itrRe->first.c_str(), itrRe->second,
                                           mapRecordTp);
    }
  }
  if (mapRecordTp.size() < 0) return false;
  bool bret = internal::MSUtil::SortMarketRecord(mapRecordTp, RecordInfo,
                                                 MarketInfo, nActvNum);

  return bret;
}
